<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-08-11 16:53:27
 * @version $Id$
 */
namespace app\agent\controller;

use think\Db;
use think\Controller;
use Godok\Org\Auth;
use think\Config;

class Mall extends Shopbase {
    
    function index(){
    	$param = Request()->param();
    	$cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1','listorder asc');
    	$cate = $cat->getTree(0);
    	$data['cate'] = $cate;
        return $this->fetch('',$data);
    }


    /**
     * 根据条件返回商品
     * @return [type] [description]
     */
    function goods(){
    	$kw = Request()->param();

        //商品分类
        $temp_category = Db::name('goods_category')->where(['cate_status'=>1])->select();
        $category = [];
        foreach ($temp_category as $k => $v) {
            $category[$v['cate_id']] = $v;
        }

    	$query = Db::table('sdzx_goods')->alias('g')
    	->field('g.goods_id,g.goods_name,g.unit,g.category_id,g.category_id_1,g.category_id_2,g.category_id_3,g.keywords,g.introduction,g.sort,g.picture,max(sval.price) as max_price,min(sval.price) as min_price,max(sval.is_hot) as is_hot,max(sval.is_recommend) as is_recommend,max(sval.is_new) as is_new,max(sval.is_cutprice) as is_cutprice,sum(sval.sales) as sales, max(sval.is_hot) as  is_promotion, b.brand_name')
    	->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.status=1')
        ->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
    	->where("sval.status=1")
        ->order('g.category_id_3 asc')
    	->group('g.goods_id');

    	if (isset($kw['cate_id']) && !empty($kw['cate_id'])) {
            $cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');
            $cate_ids = implode(',',array_column($cat->getChildren($kw['cate_id'],$category),'cate_id'));
    		$query->where("g.category_id in ({$cate_ids})");
    	}
    	if (isset($kw['is_hot']) && !empty($kw['is_hot'])) { //后面来修改
    		$query->where("is_hot=1");
    	}
    	if (isset($kw['brand']) && !empty($kw['brand'])) {
    		$query->where("g.brand_id in ({$kw['brand']})");
    	}
    	if (isset($kw['name']) && !empty($kw['name'])) {
            $name = explode(',',$kw['name']);
            $orw = '';
            foreach ($name as $key => $value) {
                $orw .= " g.goods_name like '%{$value}%' or g.keywords like '%{$value}%' or ";
            }
    		$query->where(rtrim($orw,'or '));
    	}
 
    	if (isset($kw['sales']) && !empty($kw['sales'])) {
    		$query->order('sales desc');
    	}else{
    		$query->order('g.sort desc');
    	}
    	$page = isset($kw['page'])?$params['page']:1;
    	// $list = $query->page($page,Config::get('paginate.list_rows'))->fetchSql(false)->select();
        $list = $query->select();
        $tmp_g=false;$tmp_n=0;
        $return_arr=[];
        foreach ($list as $k => $v) {
            if ( $tmp_g !== false) {
                if ($tmp_g!=$v['category_id_3']) { //加一组
                    $tmp_g=$v['category_id_3'];
                    $return_arr[$k+$tmp_n]=['is_title'=>true,'title'=>$category[$tmp_g]['cate_name'],'cate_id'=>$tmp_g];
                    $tmp_n++;
                }
            }else{
                $tmp_g = $v['category_id_3'];
                if ($tmp_g!=0) { //加一组
                    
                    $return_arr[$k+$tmp_n]=['is_title'=>true,'title'=>$category[$tmp_g]['cate_name'],'cate_id'=>$tmp_g];
                    $tmp_n++;
                }
            }
            $tmp = Db::connect([],'sval')->field('sval.*,s.supplier_name')
            ->table('sdzx_goods_specval')->alias('sval')
            ->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
            ->where(['goods_id'=>$v['goods_id']])->select();
            $return_arr[$k+$tmp_n] = $list[$k];
            $return_arr[$k+$tmp_n]['is_title']=false;

            if (sizeof($tmp)>1) {
                $return_arr[$k+$tmp_n]['specval_price'] = null;
                $return_arr[$k+$tmp_n]['unit_price'] = $list[$k]['min_price'].'-'.$list[$k]['max_price'];
            }else{
                $return_arr[$k+$tmp_n]['specval_price'] = $tmp[0]['price'];
                $return_arr[$k+$tmp_n]['unit_price'] = $tmp[0]['unit_price'];
            }
            $return_arr[$k+$tmp_n]['list']=$tmp;
        }
    	$this->success('success','',$return_arr);
    }

    /**
     * 商品搜索
     * @return [type] [description]
     */
    public function search()
    {
        $kw = Request()->param();
        $w = false;

        $query = Db::table('sdzx_goods')->alias('g')
        ->field('g.goods_id,g.goods_name,g.unit,g.category_id,g.category_id_1,g.category_id_2,g.category_id_3,g.keywords,g.introduction,g.sort,g.picture,max(sval.price) as max_price,min(sval.price) as min_price,max(sval.is_hot) as is_hot,max(sval.is_recommend) as is_recommend,max(sval.is_new) as is_new,max(sval.is_cutprice) as is_cutprice,sum(sval.sales) as sales, max(sval.is_hot) as  is_promotion, b.brand_name')
        ->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.status=1')
        ->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
        ->where("sval.status=1")
        ->order('g.category_id_3 asc')
        ->group('g.goods_id');

        if (isset($kw['cate_id']) && !empty($kw['cate_id'])) {
            //商品分类
            $temp_category = Db::name('goods_category')->where(['cate_status'=>1])->select();
            $category = [];
            foreach ($temp_category as $k => $v) {
                $category[$v['cate_id']] = $v;
            }

            $cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');
            $cate_ids = implode(',',array_column($cat->getChildren($kw['cate_id'],$category),'cate_id'));
            $query->where("g.category_id in ({$cate_ids})");
            $w = true;
        }
        if (isset($kw['is_hot']) && !empty($kw['is_hot'])) { //后面来修改
            $query->where("is_hot=1");
            $w = true;
        }
        if (isset($kw['brand']) && !empty($kw['brand'])) {
            $query->where("g.brand_id in ({$kw['brand']})");
            $w = true;
        }
        if (isset($kw['name']) && !empty($kw['name'])) {
            $name = explode(',',$kw['name']);
            foreach ($name as $key => $value) {
                $query->where("g.goods_name like '%{$value}%' or g.keywords like '%{$value}%' or b.brand_name  like '%{$value}%' ");
            }
            $w = true;
        }

        if (isset($kw['sales']) && !empty($kw['sales'])) {
            $query->order('sales desc');
        }else{
            $query->order('g.sort desc');
        }
        $page = isset($kw['page'])?$params['page']:1;
        // $list = $query->page($page,Config::get('paginate.list_rows'))->fetchSql(false)->select();
        if ($w) {
            $list = $query->select();
        }else{
            $list = [];
        }
        
        
        foreach ($list as $k => $v) {
            $tmp = Db::connect([],'sval')->field('sval.*,s.supplier_name')
            ->table('sdzx_goods_specval')->alias('sval')
            ->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
            ->where(['goods_id'=>$v['goods_id']])->select();
            if (sizeof($tmp)>1) {
                $list[$k]['specval_price'] = null;
                $list[$k]['unit_price'] = $list[$k]['min_price'].'-'.$list[$k]['max_price'];
            }else{
                $list[$k]['specval_price'] = $tmp[0]['price'];
                $list[$k]['unit_price'] = $tmp[0]['unit_price'];
                $list[$k]['specval_id'] = $tmp[0]['specval_id'];
            }
            $list[$k]['list']=$tmp;
        }

        return $this->fetch('',['list'=>$list]);
    }

    public function goodsDetail()
    {
        $goods_id = input('goods_id');
        $goods = Db::name('goods')->where(['goods_id'=>$goods_id])->find();
        $goods['img_lists'] = explode(',',$goods['img_lists']);
        array_unshift($goods['img_lists'], $goods['picture']);
        $goods['description'] = htmlspecialchars_decode($goods['description']);
        $specval = Db::name('goods_specval')->where(['goods_id'=>$goods_id])->select();
        
        $uid = $this->shop_uid;
        $num = Db::field('sum(num) as num')->name('user_cart')->where("user_id={$uid} and addbyagent>0")->find();

        return $this->fetch('',['goods'=>$goods,'specval'=>$specval,'num'=>$num['num']]);
    }


}